import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:io';

class OrderDefaultScreen extends StatefulWidget {
  const OrderDefaultScreen({super.key});

  @override
  State<OrderDefaultScreen> createState() => _OrderDefaultScreenState();
}

class _OrderDefaultScreenState extends State<OrderDefaultScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final List<String> _tabs = ['待接单', '待发货', '待收货', '售后', '历史单'];

  // 模拟订单数据
  final List<Map<String, dynamic>> _pendingOrders = [
    {
      'orderId': 'ORD20230401001',
      'createTime': '2023-04-01 10:30',
      'items': [
        {
          'name': '纯棉T恤',
          'spec': '白色/L',
          'price': 59.9,
          'quantity': 2,
          'image': 'https://via.placeholder.com/80',
        },
        {
          'name': '牛仔裤',
          'spec': '深蓝/32',
          'price': 129.0,
          'quantity': 1,
          'image': 'https://via.placeholder.com/80',
        },
      ],
      'totalAmount': 248.8,
      'status': '待接单',
    },
    {
      'orderId': 'ORD20230401002',
      'createTime': '2023-04-01 11:15',
      'items': [
        {
          'name': '运动鞋',
          'spec': '黑色/42',
          'price': 199.0,
          'quantity': 1,
          'image': 'https://via.placeholder.com/80',
        },
      ],
      'totalAmount': 199.0,
      'status': '待接单',
    },
  ];

  final List<Map<String, dynamic>> _toBeShippedOrders = [
    {
      'orderId': 'ORD20230328001',
      'createTime': '2023-03-28 09:45',
      'items': [
        {
          'name': '智能手表',
          'spec': '黑色/标准版',
          'price': 599.0,
          'quantity': 1,
          'image': 'https://via.placeholder.com/80',
        },
      ],
      'totalAmount': 599.0,
      'status': '待发货',
    },
    {
      'orderId': 'ORD20230328002',
      'createTime': '2023-03-28 14:20',
      'items': [
        {
          'name': '无线耳机',
          'spec': '白色',
          'price': 199.0,
          'quantity': 2,
          'image': 'https://via.placeholder.com/80',
        },
        {
          'name': '手机壳',
          'spec': '透明/iPhone 14',
          'price': 29.9,
          'quantity': 1,
          'image': 'https://via.placeholder.com/80',
        },
      ],
      'totalAmount': 427.9,
      'status': '待发货',
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('订单中心'),
        centerTitle: true,
        elevation: 2,
        backgroundColor: Theme.of(context).primaryColor.withValues(alpha: 0.95),
        automaticallyImplyLeading: false,
        bottom: TabBar(
          controller: _tabController,
          tabs: _tabs.map((tab) => Tab(text: tab)).toList(),
          isScrollable: true,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white.withOpacity(0.7),
          indicatorColor: Colors.white,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // 待接单
          _buildOrderList(_pendingOrders),
          // 待发货
          _buildOrderList(_toBeShippedOrders),
          // 待收货 (暂时空页面)
          const Center(child: Text('待收货页面 - 待开发')),
          // 售后 (暂时空页面)
          const Center(child: Text('售后页面 - 待开发')),
          // 历史单 (暂时空页面)
          const Center(child: Text('历史单页面 - 待开发')),
        ],
      ),
    );
  }

  Widget _buildOrderList(List<Map<String, dynamic>> orders) {
    if (orders.isEmpty) {
      return const Center(
        child: Text('暂无订单', style: TextStyle(color: Colors.grey)),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(8.0),
      itemCount: orders.length,
      itemBuilder: (context, index) {
        final order = orders[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 10),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '订单号: ${order['orderId']}',
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      order['createTime'],
                      style: const TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                  ],
                ),
                const Divider(height: 20),
                ...order['items']
                    .map<Widget>((item) => _buildOrderItem(item))
                    .toList(),
                const Divider(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '共${order['items'].length}件商品',
                      style: const TextStyle(color: Colors.grey),
                    ),
                    Text(
                      '合计: ¥${order['totalAmount'].toStringAsFixed(2)}',
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                if (order['status'] == '待接单')
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      OutlinedButton(
                        onPressed: () {},
                        child: const Text('拒绝'),
                        style: OutlinedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 20),
                        ),
                      ),
                      const SizedBox(width: 10),
                      ElevatedButton(
                        onPressed: () {},
                        child: const Text('接单'),
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 20),
                        ),
                      ),
                    ],
                  )
                else if (order['status'] == '待发货')
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton(
                        onPressed: () {},
                        child: const Text('发货'),
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 20),
                        ),
                      ),
                    ],
                  ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildOrderItem(Map<String, dynamic> item) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          // 商品图片
          Container(
            width: 60,
            height: 60,
            color: Colors.grey[200],
            child: item['image'] != null
                ? _buildNetworkImage(item['image'])
                : const Icon(Icons.image, color: Colors.grey),
          ),
          const SizedBox(width: 10),
          // 商品信息 - 使用Expanded确保文本不会溢出
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item['name'],
                  style: const TextStyle(fontWeight: FontWeight.bold),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  item['spec'],
                  style: const TextStyle(color: Colors.grey, fontSize: 12),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SizedBox(width: 10),
          // 价格和数量
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '¥${item['price'].toStringAsFixed(2)}',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 4),
              Text(
                'x${item['quantity']}',
                style: const TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 安全的网络图片加载，避免SSL证书验证错误
  Widget _buildNetworkImage(String imageUrl) {
    return Image.network(
      imageUrl,
      width: 60,
      height: 60,
      fit: BoxFit.cover,
      errorBuilder: (context, error, stackTrace) {
        return const Icon(Icons.image, color: Colors.grey);
      },
    );
  }
}
